<?php

namespace Frieza\Modules\Circle\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\cache\Circle\WhiteList;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class WhiteListController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request, Content $content): Content
    {
        $uidSet = WhiteList::getWhiteList();
        $uidStr = join(',', $uidSet);
        $uidInfo = $uidStr ? ['uid' => $uidStr] : [];
        $form = new Form($uidInfo);
        $form->textarea('uid', '白名单uid')->help('英文逗号隔开');
        $form->action(url('admin/circle/') . '/whitelist/save');
        return $content->header('种子用户白名单')->breadcrumb(
            ['text' => '圈子管理', 'url' => url('admin/circle')],
            ['text' => '种子用户白名单'])->row($form->render());
    }


    public function save(Request $request)
    {
        try {
            $param = $request->input('uid', '');
            //处理那一大坨uid
            $uidStr = str_replace(array("\r\n", "\r", "\n", " "), "", str_replace('，', ',', $param));
            $uidArr = explode(',', $uidStr);
            $uidSet = array_filter($uidArr);
            if (!empty($uidSet)) {
                //直接删除原集合，重建
                WhiteList::delWhiteList();
                WhiteList::setWhiteList($uidSet);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/circle/whitelist'))->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }
}